package com.cimpm.task.service.impl;

import com.cimpm.task.entity.TaskOrder;
import com.hby.common.callback.AutoProcessControllerPart;
import com.hby.common.entities.aspect.parameter.ParamConverter;
import com.hby.common.entities.aspect.parameter.ServiceInfo;
import com.hby.common.exceptions.AutoException;
import com.hby.common.exceptions.ExceptionEnum;
import com.hby.common.services.Impl.mian.AutoEntityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaskOrderServiceImpl extends AutoEntityServiceImpl<TaskOrder> {

    @Autowired
    private TaskFlowtaskOrderMapperServiceImpl FlowAndOrderMapperService;

    @Override
    public void addEntityOtherToRedis(TaskOrder taskOrder) {
    }

    @Override
    public void delEntityOtherFromRedis(TaskOrder taskOrder) {
    }

    @Override
    public void customService(AutoProcessControllerPart autoProcessControllerPart, ServiceInfo serviceInfo) throws Throwable {
        autoProcessControllerPart.setBeforeAddPartCallback(() -> {
            ParamConverter param = serviceInfo.getParamConverter();
            Integer flowId = param.getInt("flowId");
            Integer order = param.getInt("order");
            List<TaskOrder> taskOrders = FlowAndOrderMapperService.getSecondaryEntitiesFromPrimaryId(flowId);
            if (taskOrders.size() == 0 && order == 1) return null;
            if (taskOrders.size() != 0 && order > 1) {
                Integer max = 1;
                for (TaskOrder taskOrder : taskOrders) {
                    max = taskOrder.getOrder() > max ? taskOrder.getOrder() : max;
                }
                if (max != order - 1) throw new AutoException(ExceptionEnum.PARAM_FIELD, "无效流程顺序");
            }
            return null;
        });
    }

    public Object getFlowOrder(ParamConverter param, Integer userId, String userName) throws Throwable {
        return FlowAndOrderMapperService.getSecondaryEntitiesFromPrimaryId(param.getInt("flowId"));
    }
}
